package com.arvin.faceDetect.ui

import android.content.Intent
import android.graphics.Bitmap
import android.os.Bundle
import android.util.Log
import android.view.ActionMode
import android.view.LayoutInflater
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.Toast
import androidx.core.content.FileProvider
import androidx.core.view.isVisible
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.GridLayoutManager
import com.arvin.faceDetect.R
import com.arvin.faceDetect.adapter.FaceListAdapter
import com.arvin.faceDetect.databinding.FragmentFaceManagementBinding
import com.arvin.faceDetect.db.FaceDatabase
import com.arvin.faceDetect.db.FaceEntity
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.google.android.material.textfield.TextInputEditText
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.File
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
import java.util.zip.ZipEntry
import java.util.zip.ZipOutputStream

class FaceManagementFragment : Fragment() {
    private var _binding: FragmentFaceManagementBinding? = null
    private val binding get() = _binding!!
    
    private lateinit var faceListAdapter: FaceListAdapter
    private var isSelectionMode = false
    private var actionMode: ActionMode? = null

    private val actionModeCallback = object : ActionMode.Callback {
        override fun onCreateActionMode(mode: ActionMode, menu: Menu): Boolean {
            mode.menuInflater.inflate(R.menu.menu_face_selection, menu)
            return true
        }

        override fun onPrepareActionMode(mode: ActionMode, menu: Menu): Boolean {
            return false
        }

        override fun onActionItemClicked(mode: ActionMode, item: MenuItem): Boolean {
            return when (item.itemId) {
                R.id.action_select_all -> {
                    faceListAdapter.selectAll()
                    updateSelectionUI()
                    true
                }

                R.id.action_delete -> {
                    showDeleteConfirmDialog()
                    true
                }

                else -> false
            }
        }

        override fun onDestroyActionMode(mode: ActionMode) {
            exitSelectionMode()
        }
    }

    private fun enterSelectionMode() {
        isSelectionMode = true
        actionMode = requireActivity().startActionMode(actionModeCallback)
        binding.fabAddFace.animate()
            .scaleX(0f)
            .scaleY(0f)
            .alpha(0f)
            .setDuration(200)
            .withEndAction {
                binding.fabAddFace.visibility = View.GONE
            }
            .start()
    }

    private fun exitSelectionMode() {
        isSelectionMode = false
        actionMode?.finish()
        actionMode = null
        faceListAdapter.clearSelection()
        binding.fabAddFace.visibility = View.VISIBLE
        binding.fabAddFace.animate()
            .scaleX(1f)
            .scaleY(1f)
            .alpha(1f)
            .setDuration(200)
            .start()
    }

    private fun updateSelectionUI() {
        val selectedCount = faceListAdapter.getSelectedItems().size
        actionMode?.title = "已选择 $selectedCount 项"
        actionMode?.menu?.findItem(R.id.action_delete)?.isEnabled = selectedCount > 0
    }

    private fun showDeleteConfirmDialog() {
        val selectedItems = faceListAdapter.getSelectedItems()
        if (selectedItems.isEmpty()) {
            return
        }

        MaterialAlertDialogBuilder(
            requireContext(),
            R.style.ThemeOverlay_Material3_MaterialAlertDialog_Centered
        )
            .setTitle("删除确认")
            .setMessage("确定要删除选中的 ${selectedItems.size} 个人脸吗？此操作不可恢复。")
            .setIcon(R.drawable.ic_warning)
            .setPositiveButton("删除") { _, _ ->
                lifecycleScope.launch {
                    try {
                        withContext(Dispatchers.IO) {
                            FaceDatabase.getDatabase(requireContext())
                                .faceDao()
                                .deleteFaces(selectedItems)
                        }
                        Toast.makeText(
                            requireContext(),
                            "已删除${selectedItems.size}个人脸",
                            Toast.LENGTH_SHORT
                        ).show()
                        exitSelectionMode()
                    } catch (e: Exception) {
                        Toast.makeText(
                            requireContext(),
                            "删除失败：${e.message}",
                            Toast.LENGTH_SHORT
                        ).show()
                    }
                }
            }
            .setNegativeButton("取消", null)
            .show()
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setHasOptionsMenu(true)

        // 初始化adapter
        faceListAdapter = FaceListAdapter(
            onItemClick = { face: FaceEntity ->
                if (isSelectionMode) {
                    faceListAdapter.toggleSelection(face)
                    updateSelectionUI()
                } else {
                    showEditFaceDialog(face)
                }
            },
            onItemLongClick = { face: FaceEntity ->
                if (!isSelectionMode) {
                    enterSelectionMode()
                    faceListAdapter.toggleSelection(face)
                    updateSelectionUI()
                }
                true
            }
        )
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentFaceManagementBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        setupToolbar()
        setupRecyclerView()
        observeFaces()
        setupFabAddFace()
    }

    private fun setupToolbar() {
        binding.toolbar.setNavigationOnClickListener {
            if (isSelectionMode) {
                cancelSelection()
            } else {
                findNavController().navigateUp()
            }
        }

        binding.btnExport.setOnClickListener {
            exportFaceData()
        }
    }

    private fun setupRecyclerView() {
        binding.rvFaces.apply {
            layoutManager = GridLayoutManager(context, 3)
            adapter = faceListAdapter
        }
    }

    private fun setupFabAddFace() {
        binding.fabAddFace.setOnClickListener {
            findNavController().navigate(R.id.action_navigation_face_management_to_faceAutoCollectFragment)
        }
    }

    private fun observeFaces() {
        viewLifecycleOwner.lifecycleScope.launch {
            FaceDatabase.getDatabase(requireContext())
                .faceDao()
                .getAllFaces()
                .collect { faces ->
                    faceListAdapter.submitList(faces)
                    updateEmptyView(faces.isEmpty())
                }
        }
    }

    private fun updateEmptyView(isEmpty: Boolean) {
        binding.tvEmpty.isVisible = isEmpty
        binding.rvFaces.isVisible = !isEmpty
    }

    private fun showFaceDetailDialog(face: FaceEntity) {
        MaterialAlertDialogBuilder(requireContext())
            .setTitle("人脸详情")
            .setMessage(
                """
                ID: ${face.id}
                名称: ${face.name}
                创建时间: ${face.getFormattedCreateTime()}
                """.trimIndent()
            )
            .setPositiveButton("编辑") { _, _ ->
                showEditFaceDialog(face)
            }
            .setNegativeButton("删除") { _, _ ->
                showDeleteConfirmDialog()
            }
            .setNeutralButton("关闭", null)
            .show()
    }

    private fun showEditFaceDialog(face: FaceEntity) {
        val dialogView = LayoutInflater.from(requireContext())
            .inflate(R.layout.dialog_edit_face, null)

        dialogView.findViewById<ImageView>(R.id.ivFace).setImageBitmap(face.faceImage)
        val etName = dialogView.findViewById<TextInputEditText>(R.id.etName)
        etName.setText(face.name)

        MaterialAlertDialogBuilder(requireContext())
            .setTitle("编辑人脸")
            .setView(dialogView)
            .setPositiveButton("保存") { _, _ ->
                val newName = etName.text.toString()
                if (newName.isNotBlank()) {
                    updateFaceName(face, newName)
                }
            }
            .setNegativeButton("取消", null)
            .show()
    }

    private fun updateFaceName(face: FaceEntity, newName: String) {
        lifecycleScope.launch {
            try {
                val updatedFace = face.copy(name = newName)
                withContext(Dispatchers.IO) {
                    FaceDatabase.getDatabase(requireContext())
                        .faceDao()
                        .updateFace(updatedFace)
                }
                Toast.makeText(context, "更新成功", Toast.LENGTH_SHORT).show()
            } catch (e: Exception) {
                Toast.makeText(context, "更新失败: ${e.message}", Toast.LENGTH_SHORT).show()
            }
        }
    }

    override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
        inflater.inflate(R.menu.menu_face_management, menu)
        super.onCreateOptionsMenu(menu, inflater)
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        return when (item.itemId) {
            R.id.action_search -> {
                val searchView = item.actionView as androidx.appcompat.widget.SearchView
                setupSearchView(searchView)
                true
            }
            R.id.action_export -> {
                exportFaceData()
                true
            }
            R.id.action_select_all -> {
                selectAllFaces()
                true
            }
            R.id.action_delete -> {
                showDeleteSelectedDialog()
                true
            }
            R.id.action_cancel_selection -> {
                cancelSelection()
                true
            }
            else -> super.onOptionsItemSelected(item)
        }
    }

    private fun setupSearchView(searchView: androidx.appcompat.widget.SearchView) {
        searchView.setOnQueryTextListener(object :
            androidx.appcompat.widget.SearchView.OnQueryTextListener {
            override fun onQueryTextSubmit(query: String?): Boolean {
                return false
            }

            override fun onQueryTextChange(newText: String?): Boolean {
                searchFaces(newText.orEmpty())
                return true
            }
        })
    }

    private fun searchFaces(query: String) {
        lifecycleScope.launch {
            try {
                val faces = withContext(Dispatchers.IO) {
                    if (query.isBlank()) {
                        FaceDatabase.getDatabase(requireContext()).faceDao().getAllFacesList()
                    } else {
                        FaceDatabase.getDatabase(requireContext()).faceDao().searchFaces("%$query%")
                    }
                }
                faceListAdapter.submitList(faces)
                updateEmptyView(faces.isEmpty())
            } catch (e: Exception) {
                Toast.makeText(context, "搜索失败: ${e.message}", Toast.LENGTH_SHORT).show()
            }
        }
    }

    private fun selectAllFaces() {
        val currentFaces = faceListAdapter.currentList
        if (currentFaces.isEmpty()) return

        faceListAdapter.selectAll()
        updateSelectionUI()
    }

    private fun showDeleteSelectedDialog() {
        if (faceListAdapter.getSelectedItems().isEmpty()) return

        MaterialAlertDialogBuilder(requireContext())
            .setTitle("批量删除确认")
            .setMessage("确定要删除选中的 ${faceListAdapter.getSelectedItems().size} 个人脸吗？")
            .setPositiveButton("删除") { _, _ ->
                deleteSelectedFaces()
            }
            .setNegativeButton("取消", null)
            .show()
    }

    private fun deleteSelectedFaces() {
        lifecycleScope.launch {
            try {
                withContext(Dispatchers.IO) {
                    val facesToDelete = FaceDatabase.getDatabase(requireContext())
                        .faceDao()
                        .getFacesByIds(faceListAdapter.getSelectedItems().map { it.id })
                    FaceDatabase.getDatabase(requireContext())
                        .faceDao()
                        .deleteFaces(facesToDelete)
                }
                Toast.makeText(
                    context,
                    "已删除 ${faceListAdapter.getSelectedItems().size} 项",
                    Toast.LENGTH_SHORT
                ).show()
                cancelSelection()
            } catch (e: Exception) {
                Toast.makeText(context, "删除失败: ${e.message}", Toast.LENGTH_SHORT).show()
            }
        }
    }

    private fun cancelSelection() {
        exitSelectionMode()
        faceListAdapter.notifyDataSetChanged()
    }

    override fun onDestroyView() {
        super.onDestroyView()
        exitSelectionMode()
        _binding = null
    }

    override fun onPause() {
        super.onPause()
        exitSelectionMode()
    }

    // 扩展函数：格式化创建时间
    private fun FaceEntity.getFormattedCreateTime(): String {
        val dateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault())
        return dateFormat.format(Date(createTime))
    }

    // 扩展属性：是否被选中
    private val FaceEntity.isSelected: Boolean
        get() = faceListAdapter.getSelectedItems().contains(this)

    private fun exportFaceData() {
        viewLifecycleOwner.lifecycleScope.launch {
            try {
                // 获取所有人脸数据
                val faces = withContext(Dispatchers.IO) {
                    FaceDatabase.getDatabase(requireContext())
                        .faceDao()
                        .getAllFacesList()
                }

                if (faces.isEmpty()) {
                    Toast.makeText(context, "没有可导出的人脸数据", Toast.LENGTH_SHORT).show()
                    return@launch
                }

                // 创建导出目录
                val exportDir = File(requireContext().getExternalFilesDir(null), "face_export")
                if (!exportDir.exists()) {
                    exportDir.mkdirs()
                }

                // 创建导出文件
                val timestamp =
                    SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(Date())
                val exportFile = File(exportDir, "face_data_${timestamp}")
                if (!exportFile.exists()) {
                    exportFile.mkdirs()
                }

                // 导出数据
                withContext(Dispatchers.IO) {
                    // 导出人脸信息到CSV文件
                    val csvFile = File(exportFile, "face_info.csv")
                    csvFile.bufferedWriter().use { writer ->
                        writer.write("ID,姓名,创建时间\n")
                        faces.forEach { face ->
                            writer.write("${face.id},${face.name},${face.getFormattedCreateTime()}\n")
                        }
                    }

                    // 导出人脸图片
                    faces.forEach { face ->
                        val imageFile = File(exportFile, "face_${face.id}.jpg")
                        imageFile.outputStream().use { output ->
                            face.faceImage?.compress(Bitmap.CompressFormat.JPEG, 100, output)
                        }
                    }
                }

                // 创建ZIP文件
                val zipFile = File(exportDir, "face_data_${timestamp}.zip")
                withContext(Dispatchers.IO) {
                    ZipOutputStream(zipFile.outputStream()).use { zip ->
                        exportFile.walkTopDown().forEach { file ->
                            if (file.isFile) {
                                val entry = ZipEntry(file.relativeTo(exportFile).path)
                                zip.putNextEntry(entry)
                                file.inputStream().use { input ->
                                    input.copyTo(zip)
                                }
                                zip.closeEntry()
                            }
                        }
                    }
                }

                // 删除临时目录
                exportFile.deleteRecursively()

                // 分享ZIP文件
                val uri = FileProvider.getUriForFile(
                    requireContext(),
                    "${requireContext().packageName}.provider",
                    zipFile
                )

                val intent = Intent(Intent.ACTION_SEND).apply {
                    type = "application/zip"
                    putExtra(Intent.EXTRA_STREAM, uri)
                    addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
                }

                startActivity(Intent.createChooser(intent, "分享导出文件"))

                // 记录日志
                Log.i("FaceManagement", "导出${faces.size}个人脸数据到${zipFile.name}")

                Toast.makeText(context, "导出成功", Toast.LENGTH_SHORT).show()
            } catch (e: Exception) {
                Log.e("FaceManagement", "导出人脸数据失败", e)
                Toast.makeText(context, "导出失败：${e.message}", Toast.LENGTH_SHORT).show()
            }
        }
    }
} 